package com.hue.concurrent.day05;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/*
    条件变量的使用
 */
public class Demo02 {
    private static ReentrantLock room = new ReentrantLock();
    private static Condition condition1 = room.newCondition();
    private static Condition condition2 = room.newCondition();
    private static boolean flag1 = false;
    private static boolean flag2 = false;


    public static void main(String[] args) {
        new Thread(() -> {
            room.lock();
            try {
                while (!flag1) {
                    System.out.println("没有烟等一下");
                    try {
                        condition1.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("烟到了");
                }
            }finally {
                room.unlock();
            }
        }).start();

        new Thread(() -> {
            room.lock();
            try {
                while (!flag2) {
                    System.out.println("没有外卖等一下");
                    try {
                        condition2.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("外卖到了");
                }
            }finally {
                room.unlock();
            }
        }).start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            room.lock();
            try {

                System.out.println("送外卖了");
                flag2 = true;
                condition2.signal();
            }finally {
                room.unlock();
            }
        }).start();
    }
}
